<template>
    <!-- 面包屑导航区域 -->
    <div>
        <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>


        <el-card>
            <!-- 搜索与添加区域 -->
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input v-model="queryInfo.query" placeholder="请输入内容" clearable @clear="getUserList">
                        <template #append>
                            <el-button :icon="Search" @click="getUserList" />
                        </template>
                    </el-input></el-col>
                <el-col :span="4">
                    <el-button v-if="hasPermission('添加用户功能')" type="primary" icon="Plus" @click="dialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
            <!-- 用户列表区域 -->
            <el-table :data="userlist" stripe border style="width: 100%; height: 100%" class="user-table" fit>
                <el-table-column type="index" label="#" width="60" />
                <el-table-column prop="username" label="姓名" min-width="120" />
                <el-table-column prop="email" label="邮箱" min-width="180" />
                <el-table-column prop="phone_number" label="电话" min-width="140" />
                <el-table-column prop="role_name" label="角色" min-width="120">
                    <template #default="scope">
                        {{ scope.row.role_description }}
                        <!-- {{ scope.row.role_name === 'admin' ? '管理员' :
                            scope.row.role_name === 'super_admin' ? '超级管理员' :
                                scope.row.role_name === 'user' ? '普通用户' :
                                    scope.row.role_name }} -->
                    </template>
                </el-table-column>
                <!-- <el-table-column prop="mg_state" label="状态" min-width="100">
                    <template #default="scope">
                        <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)" />
                    </template>
                </el-table-column> -->
                <el-table-column prop="created_at" label="注册时间" min-width="180">
                    <template #default="scope">
                        {{ new Date(scope.row.created_at).toLocaleString('zh-CN', {
                            year: 'numeric',
                            month: '2-digit',
                            day: '2-digit',
                            hour: '2-digit',
                            minute: '2-digit',
                            second: '2-digit',
                            hour12: false
                        }).replace(/\//g, '-') }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" min-width="280" fixed="right">
                    <template #default="scope">
                        <div class="operation-buttons">
                            <el-button v-if="hasPermission('修改用户功能')" type="primary" :icon="Edit" size="small" @click="handleEdit(scope.row)">修改</el-button>
                            <el-button v-if="hasPermission('删除用户功能')" type="danger" :icon="Delete" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
                            <el-button v-if="hasPermission('分配角色功能')" type="warning" :icon="Setting" size="small" @click="handleRole(scope.row)">分配角色</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页区域 -->
            <el-pagination v-model="queryInfo.currentPage" :page-size="queryInfo.pageSize"
                :page-sizes="[1, 8, 16, 50]" :background="true" layout="total, sizes, prev, pager, next, jumper"
                :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </el-card>

        <!-- 添加用户的对话框 -->
        <el-dialog v-model="dialogVisible" title="添加用户" width="50%" @close="dialogClosed">
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password" type="password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="phone_number">
                    <el-input v-model="addForm.phone_number"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="addUser">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 修改用户的对话框 -->
        <el-dialog v-model="editDialogVisible" title="修改用户信息" width="50%" @close="editDialogClosed">
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
                <el-form-item label="用户名">
                    <el-input v-model="editForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="phone_number">
                    <el-input v-model="editForm.phone_number"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="editUser">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 分配角色的对话框 -->
        <el-dialog v-model="roleDialogVisible" title="分配角色" width="50%" @close="roleDialogClosed" class="role-assignment-dialog">
            <div class="role-info">
                <div class="info-item">
                    <span class="label">当前用户：</span>
                    <span class="value">{{ roleForm.username }}</span>
                </div>
                <div class="info-item">
                    <span class="label">当前角色：</span>
                    <span class="value">
                        <el-tag
                            :type="roleForm.role_name === 'super_admin' ? 'danger' : roleForm.role_name === 'admin' ? 'warning' : 'info'"
                            size="small"
                        >
                            {{ roleForm.role_name === 'admin' ? '管理员' : 
                               roleForm.role_name === 'super_admin' ? '超级管理员' : 
                               roleForm.role_name === 'user' ? '普通用户' : 
                               roleForm.role_name || '无' }}
                        </el-tag>
                    </span>
                </div>
                <div class="info-item">
                    <span class="label">分配新角色：</span>
                    <el-select 
                        v-model="selectedRoleId" 
                        placeholder="请选择角色"
                        class="role-select"
                    >
                        <el-option 
                            v-for="item in rolesList" 
                            :key="item.id" 
                            :label="item.name" 
                            :value="item.id"
                        >
                            <template #default>
                                <el-tag
                                    :type="item.name === 'super_admin' ? 'danger' : item.name === 'admin' ? 'warning' : 'info'"
                                    size="small"
                                    style="margin-right: 8px"
                                >
                                    {{ item.name === 'admin' ? '管理员' :
                                       item.name === 'super_admin' ? '超级管理员' :
                                       item.name === 'user' ? '普通用户' :
                                       item.name }}
                                </el-tag>
                                <span>{{ item.description || '无描述' }}</span>
                            </template>
                        </el-option>
                    </el-select>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="roleDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="assignRole">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ArrowRight } from '@element-plus/icons-vue'
import { onMounted, ref } from 'vue'
import { Search, Edit, Delete, Setting } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from "@/utils/http" // 确保已正确配置 Axios 工具文件
import { debounce } from 'lodash'
// 检查权限
const hasPermission = (permission) => {
    const userFunctions = JSON.parse(sessionStorage.getItem('permissions') || '[]')
    return userFunctions.includes(permission)
}

// 查询参数对象
const queryInfo = ref({
    query: '',
    pagenum: 1,
    pagesize: 8
})

// 用户列表数据
const userlist = ref([])
// 总数据条数
const total = ref(0)

// 获取用户列表数据
const getUserList = debounce(async () => {
    // 搜索时重置页码到第一页
    if (queryInfo.value.query !== '') {
        queryInfo.value.pagenum = 1
    }
    const { data: res } = await axios.get('/user/list/', { 
  params: {
    query: queryInfo.value.query,
    current_page: queryInfo.value.pagenum,
    page_size: queryInfo.value.pagesize
  }
})
    if (res.code !== 200) return ElMessage.error(res.message)
    // 根据搜索关键词筛选数据
    const filteredData = queryInfo.value.query
        ? res.data.filter(user =>
            (user.username?.toLowerCase().includes(queryInfo.value.query.toLowerCase()) ?? false) ||
            (user.email?.toLowerCase().includes(queryInfo.value.query.toLowerCase()) ?? false) ||
            (user.phone_number?.includes(queryInfo.value.query) ?? false)
        )
        : res.data
    total.value = filteredData.length
    // 根据当前页码和每页显示数量计算要显示的数据
    const startIndex = (queryInfo.value.pagenum - 1) * queryInfo.value.pagesize
    const endIndex = startIndex + queryInfo.value.pagesize
    userlist.value = filteredData.slice(startIndex, endIndex)
}, 300)

// 监听 pagesize 改变事件
const handleSizeChange = (newSize) => {
    queryInfo.value.pagesize = newSize
    queryInfo.value.pagenum = 1
    console.log('pagesize changed:', newSize)
    getUserList()
}

// 监听页码值改变事件
const handleCurrentChange = (newPage) => {
    queryInfo.value.pagenum = newPage
    console.log('pagenum changed:', newPage)
    getUserList()
}

// 添加用户对话框显示状态
const dialogVisible = ref(false)

// 添加用户的表单数据
const addForm = ref({
    username: '',
    password: '',
    email: '',
    phone_number: ''
})

// 添加用户的表单验证规则
const addFormRules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 10, message: '用户名长度在 3 到 10 个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 15, message: '密码长度在 6 到 15 个字符', trigger: 'blur' }
    ],
    email: [
        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ],
    phone_number: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ]
}

// 添加用户的表单引用
const addFormRef = ref()

// 添加用户对话框关闭事件
const dialogClosed = () => {
    addFormRef.value.resetFields()
}

// 添加用户
const addUser = () => {
    addFormRef.value.validate(async valid => {
        if (!valid) return
        try {
            const formData = {
                username: addForm.value.username,
                password: addForm.value.password,
                email: addForm.value.email,
                phone_number: addForm.value.phone_number
            }
            const { data: res } = await axios.post('/add_user/', formData, {
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            })

            if (res.code !== 200) {
                ElMessage.error(res.message || '添加用户失败')
                return
            }
            ElMessage.success('添加用户成功！')
            dialogVisible.value = false
            getUserList()
        } catch (error) {
            console.error('添加用户时发生错误:', error)
            ElMessage.error('添加用户失败，请稍后重试')
        }
    })
}

// 修改用户对话框显示状态
const editDialogVisible = ref(false)

// 修改用户的表单数据
const editForm = ref({
    id: '',
    username: '',
    email: '',
    phone_number: ''
})

// 修改用户的表单验证规则
const editFormRules = {
    email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ],
    phone_number: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ]
}

// 修改用户的表单引用
const editFormRef = ref()

// 修改用户信息
const handleEdit = (row) => {
    editDialogVisible.value = true
    editForm.value = { ...row }
}

// 修改用户对话框关闭事件
const editDialogClosed = () => {
    editFormRef.value.resetFields()
}

// 修改用户信息
const editUser = () => {
    editFormRef.value.validate(async valid => {
        if (!valid) return
        const { data: res } = await axios.put(`/user/update/${editForm.value.id}/`, editForm.value)
        // console.log("修改前的用户信息：",editForm.value)
        if (res.code !== 200) return ElMessage.error(res.message)
        ElMessage.success('修改用户信息成功！')
        editDialogVisible.value = false
        getUserList()
    })
}

// 删除用户
const handleDelete = (id) => {
    ElMessageBox.confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        const { data: res } = await axios.delete(`/user/delete/${id}/`)
        if (res.code !== 200) return ElMessage.error(res.message)
        ElMessage.success('删除成功！')
        getUserList()
    }).catch(() => {
        ElMessage.info('已取消删除')
    })
}

// 角色列表数据
const rolesList = ref([])
const roleDialogVisible = ref(false)
const roleForm = ref({})
// 获取所有角色列表
const getRolesList = async () => {
    const { data: res } = await axios.get('role/list/')
    console.log("后端返回过来的角色列表信息：",res)
    if (res.code !== 200) return ElMessage.error(res.message)
    rolesList.value = res.data
}
// 选中的角色ID
const selectedRoleId = ref('')

// 监听用户状态改变
const userStateChanged = async (userInfo) => {
    const { data: res } = await axios.put(`/user/${userInfo.id}/state/${userInfo.mg_state}/`)
    if (res.code !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return ElMessage.error(res.message)
    }
    ElMessage.success('更新用户状态成功！')
    // console.log(userInfo)
}

// 展示分配角色的对话框
const handleRole = async (row) => {
    roleForm.value = row
    await getRolesList()
    selectedRoleId.value = row.role_id
    roleDialogVisible.value = true
}

// 分配角色对话框关闭事件
const roleDialogClosed = () => {
    roleForm.value = {}
    selectedRoleId.value = ''
}

// 分配角色
const assignRole = async () => {
    if (!selectedRoleId.value) {
        return ElMessage.warning('请选择要分配的角色！')
    }
    try {
        const selectedRole = rolesList.value.find(role => role.id === selectedRoleId.value)
        if (!selectedRole) {
            return ElMessage.warning('所选角色无效！')
        }
        const { data: res } = await axios.post('/role/assign_functions/', {
            role_name: selectedRole.name,
            user_id: roleForm.value.id,
            role_id: selectedRole.id  // 添加role_id字段
        })
        if (res.code !== 200) return ElMessage.error(res.message)

        // 更新当前用户的角色信息
        const userIndex = userlist.value.findIndex(user => user.id === roleForm.value.id)
        if (userIndex !== -1) {
            userlist.value[userIndex].role_name = selectedRole.name
            userlist.value[userIndex].role_id = selectedRole.id
        }
        roleForm.value.role_name = selectedRole.name
        roleForm.value.role_id = selectedRole.id

        ElMessage.success(res.message)
        roleDialogVisible.value = false
        // 重新获取用户列表以确保数据同步
        await getUserList()
    } catch (error) {
        console.error('分配角色时发生错误:', error)
        ElMessage.error('分配角色失败，请稍后重试')
    }
}

onMounted(() => {
    getUserList()
})

</script>

<style scoped>
.user-table {
    max-width: 100%;
    overflow-x: auto;
    height: calc(100vh - 250px);
    margin-bottom: 20px;
}

.el-table {
    height: 100%;
}

.operation-buttons {
    display: flex;
    flex-direction: row;
    gap: 5px;
    justify-content: space-between;
}
.el-pagination {
                display: flex;
                justify-content: center;
                margin-top: 20px;
            }
            
.operation-buttons .el-button {
    margin: 0;
    padding: 4px 8px;
    font-size: 12px;
    min-width: 60px;
}

.role-assignment-dialog :deep(.el-dialog__body) {
    padding: 20px 30px;
}

.role-info {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.info-item {
    display: flex;
    align-items: center;
}

.info-item .label {
    width: 100px;
    color: #606266;
    font-weight: 500;
}

.info-item .value {
    flex: 1;
}

.role-select {
    width: 300px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding-top: 20px;
}
</style>


